import csv

from django.shortcuts import render, redirect, get_object_or_404
from django.http import JsonResponse, HttpResponse
from .models import Customer
from django.views.decorators.csrf import csrf_exempt


# 客户列表视图
@csrf_exempt
def customer_list(request):
    customers = Customer.objects.all()
    return render(request, 'customer-list.html', {'customers': customers})


def export_customers_csv(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="customers.csv"'

    # 客户数据的字段名，中文表头
    field_names = ['客户编号', '客户名称', '客户简称', '地址', '公司电话', '邮件', '联系人', '联系人电话', '备注']

    # 写入 CSV 文件
    writer = csv.writer(response, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    writer.writerow([name for name in field_names])  # 写入表头

    # 获取所有客户数据
    customers = Customer.objects.all()

    # 将客户数据写入 CSV 文件
    for customer in customers:
        writer.writerow([
            customer.Cid,
            customer.CcompanyName,
            customer.CcompanySName,
            customer.CcompanyAddress,
            customer.CcompanyPhone,
            customer.Cemail,
            customer.Cname,
            customer.CtelPhone,
            customer.other,
        ])

    # 设置 UTF-8 with BOM 编码格式
    response.write('\ufeff'.encode('utf-8'))

    return response


# 添加客户视图
@csrf_exempt
def customer_add(request):
    if request.method == 'POST':
        Cid = request.POST.get('Cid')
        CcompanyName = request.POST.get('CcompanyName')
        CcompanySName = request.POST.get('CcompanySName')
        CcompanyAddress = request.POST.get('CcompanyAddress')
        CcompanyPhone = request.POST.get('CcompanyPhone')
        Cemail = request.POST.get('Cemail')
        Cname = request.POST.get('Cname')
        CtelPhone = request.POST.get('CtelPhone')
        other = request.POST.get('other')
        Customer.objects.create(
            Cid=Cid,
            CcompanyName=CcompanyName,
            CcompanySName=CcompanySName,
            CcompanyAddress=CcompanyAddress,
            CcompanyPhone=CcompanyPhone,
            Cemail=Cemail,
            Cname=Cname,
            CtelPhone=CtelPhone,
            other=other
        )
        return JsonResponse({'code': '200', 'message': '添加成功'})
    return render(request, 'customer-add.html')


# 根据ID查找客户视图
def customer_find_by_id(request):
    Cid = request.GET.get('id')
    customer = get_object_or_404(Customer, Cid=Cid)
    return render(request, 'customer-update.html', {'customer': customer})


# 修改客户视图
@csrf_exempt
def customer_update(request):
    if request.method == 'POST':
        Cid = request.POST.get('Cid')
        customer = get_object_or_404(Customer, Cid=Cid)
        customer.CcompanyName = request.POST.get('CcompanyName')
        customer.CcompanySName = request.POST.get('CcompanySName')
        customer.CcompanyAddress = request.POST.get('CcompanyAddress')
        customer.CcompanyPhone = request.POST.get('CcompanyPhone')
        customer.Cemail = request.POST.get('Cemail')
        customer.Cname = request.POST.get('Cname')
        customer.CtelPhone = request.POST.get('CtelPhone')
        customer.other = request.POST.get('other')
        customer.save()
        return JsonResponse({'code': 200, 'message': '客户信息更新成功'})
    else:
        return JsonResponse({'code': 400, 'message': '请求方法错误'})


# 删除客户视图
@csrf_exempt
def customer_delete(request, customer_id):
    try:
        customer = Customer.objects.get(Cid=customer_id)
        customer.delete()
        return JsonResponse({'code': 200, 'message': '删除成功'})
    except Customer.DoesNotExist:
        return JsonResponse({'code': 404, 'message': '客户不存在'})
